<template>
  <div class="warning-container">
    <div class="chart-header">
      <h2>币种预警统计</h2>
      <div class="refresh-control">
        <span>刷新间隔：</span>
        <el-select v-model="refreshInterval" placeholder="选择刷新间隔" @change="updateRefreshInterval">
          <el-option :value="10000" label="10秒"></el-option>
          <el-option :value="30000" label="30秒"></el-option>
          <el-option :value="60000" label="1分钟"></el-option>
          <el-option :value="300000" label="5分钟"></el-option>
        </el-select>
        <el-button type="primary" size="small" @click="fetchWarningData" :loading="loading">立即刷新</el-button>
        <span class="last-refresh">最后更新: {{ lastRefreshTime }}</span>
      </div>
    </div>
    <div class="chart-container" v-loading="loading">
      <div ref="chartRef" class="chart"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

const chartRef = ref(null)
const loading = ref(false)
let chartInstance = null
let refreshTimer = null
const refreshInterval = ref(30000) // 默认30秒刷新一次
const lastRefreshTime = ref('--')

// 获取预警数据
const fetchWarningData = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://127.0.0.1:1234/symbols/get')
    if (response.data && response.data.length > 0) {
      renderChart(response.data)
      // 更新最后刷新时间
      updateLastRefreshTime()
    } else {
      ElMessage.warning('暂无预警数据')
      // 即使没有数据也更新刷新时间
      updateLastRefreshTime()
    }
  } catch (error) {
    console.error('获取预警数据失败:', error)
    ElMessage.error('获取预警数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 渲染图表
const renderChart = (data) => {
  if (!chartRef.value) return
  
  // 确保图表实例存在
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value, null, {
      renderer: 'canvas',
      useDirtyRect: false
    })
  }
  
  // 对数据按照预警次数从大到小排序
  const sortedData = [...data].sort((a, b) => b.warnCount - a.warnCount)
  
  // 处理排序后的数据
  const symbolNames = sortedData.map(item => item.symbolName)
  const warnCounts = sortedData.map(item => item.warnCount)
  // 提取成交量和涨幅信息
  const tradingVolumes = sortedData.map(item => item.symbolDto?.tradingVolume || '')
  const increaseRates = sortedData.map(item => item.symbolDto?.increaseRate || '')
  
  // 图表配置
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '5%',
      right: '20%',
      bottom: '5%',
      top: '5%',
      containLabel: true
    },
    yAxis: {
      type: 'category',
      data: symbolNames,
      inverse: true,
      axisLabel: {
        interval: 0
      }
    },
    xAxis: {
      type: 'value',
      name: '预警次数'
    },
    series: [
      {
        name: '预警次数',
        type: 'bar',
        barWidth: '60%',
        data: warnCounts,
        label: {
          show: true,
          position: 'right',
          formatter: function(params) {
            const index = params.dataIndex;
            const tradingVolume = tradingVolumes[index] || '';
            const increaseRate = increaseRates[index] || '';
            return `${params.value}\n${tradingVolume}\n${increaseRate}`;
          },
          fontSize: 14,
          color: '#333',
          lineHeight: 20,
          rich: {
            volume: {
              fontSize: 12,
              color: '#666'
            },
            rate: {
              fontSize: 12,
              color: '#666'
            }
          }
        },
        itemStyle: {
          color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        }
      }
    ]
  }
  
  // 设置图表配置
  chartInstance.setOption(option)
}

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    // 强制设置图表大小适应容器
    chartInstance.resize({
      width: 'auto',
      height: 'auto'
    })
    // 当窗口大小变化时，重新设置图表配置以适应新尺寸
    const currentOption = chartInstance.getOption()
    chartInstance.setOption(currentOption, true)
  }
}

// 更新刷新间隔
const updateRefreshInterval = () => {
  // 清除旧的定时器
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
  
  // 设置新的定时器
  refreshTimer = setInterval(() => {
    fetchWarningData()
  }, refreshInterval.value)
  
  ElMessage.success(`刷新间隔已设置为${refreshInterval.value/1000}秒`)
}

// 更新最后刷新时间
const updateLastRefreshTime = () => {
  const now = new Date()
  const hours = now.getHours().toString().padStart(2, '0')
  const minutes = now.getMinutes().toString().padStart(2, '0')
  const seconds = now.getSeconds().toString().padStart(2, '0')
  lastRefreshTime.value = `${hours}:${minutes}:${seconds}`
}

onMounted(() => {
  fetchWarningData()
  window.addEventListener('resize', handleResize)
  
  // 设置定时器，定期刷新数据
  refreshTimer = setInterval(() => {
    fetchWarningData()
  }, refreshInterval.value)
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
  
  // 清除定时器
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
})
</script>

<style scoped>
.warning-container {
  padding: 20px;
}

.chart-header {
  margin-bottom: 20px;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.refresh-control {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.last-refresh {
  color: #909399;
  font-size: 14px;
}

.chart-container {
  width: 100%;
  height: calc(100vh - 180px);
  min-height: 400px;
  min-width: 800px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  overflow-x: hidden;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>